package com.example.blog.controller;


import com.example.blog.pojo.CodeRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/code")
public class CodeExecutionController {

    @PostMapping("/execute")
    public ResponseEntity<?> executeCode(@RequestBody CodeRequest codeRequest) {
        // 1. 检查用户代码是否包含危险命令
        if (codeRequest.getCode().contains("System.exit") || codeRequest.getCode().contains("Runtime.getRuntime().exec")) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Prohibited operation detected in code.");
        }

        // 2. 从用户代码中提取类名，使用正则表达式
        String className = extractClassName(codeRequest.getCode());
        if (className == null || className.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No valid class name found in the code.");
        }

        // 3. 保存用户上传的代码到临时文件，文件名为提取到的类名
        String fileName = className + ".java";  // 生成文件名
        File javaFile = new File(fileName);
        try (FileWriter writer = new FileWriter(javaFile, false)) {
            writer.write(codeRequest.getCode());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error writing code to file");
        }

        try {
            // 4. 编译代码
            ProcessBuilder compileBuilder = new ProcessBuilder("javac", "-encoding", "GBK", fileName);
            Process compileProcess = compileBuilder.start();
            compileProcess.waitFor(10, TimeUnit.SECONDS); // 等待编译完成，超时时间设置为 10 秒

            if (compileProcess.exitValue() != 0) {
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream(), Charset.forName("GBK")));
                StringBuilder errorMessage = new StringBuilder();
                String line;
                while ((line = errorReader.readLine()) != null) {
                    errorMessage.append(line).append("\n");
                }
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Compilation Error: \n" + errorMessage);
            }

            // 5. 执行代码
            ProcessBuilder executeBuilder = new ProcessBuilder("java", "-cp", ".", className);
            executeBuilder.redirectErrorStream(true);  // 将错误流和标准流合并
            Process executeProcess = executeBuilder.start();

            boolean finished = executeProcess.waitFor(10, TimeUnit.SECONDS); // 等待代码执行完成，超时时间为 10 秒

            if (!finished) {
                executeProcess.destroy();
                return ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body("Execution timeout");
            }

            // 6. 读取输出
            BufferedReader outputReader = new BufferedReader(new InputStreamReader(executeProcess.getInputStream(), Charset.forName("GBK")));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = outputReader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 返回 HTTP 200 成功，包含代码执行的标准输出
            return ResponseEntity.ok(output.toString());

        } catch (IOException | InterruptedException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error during execution");
        } finally {
            // 7. 确保删除临时文件
            try {
                // 删除 .java 文件
                if (javaFile.exists()) {
                    javaFile.delete();  // 删除 .java 文件
                }

                // 删除 .class 文件
                File classFile = new File(className + ".class");
                if (classFile.exists()) {
                    classFile.delete();  // 删除编译后的 .class 文件
                }

            } catch (Exception e) {
                // 如果删除失败，可以记录日志或执行其他逻辑
                System.err.println("Failed to delete file: " + e.getMessage());
            }
        }
    }

    // 使用正则表达式提取用户代码中的类名
    private String extractClassName(String code) {
        Pattern pattern = Pattern.compile("class\\s+(\\w+)");  // 匹配类定义，例如 "class ClassName"
        Matcher matcher = pattern.matcher(code);
        if (matcher.find()) {
            return matcher.group(1);  // 返回第一个捕获的类名
        }
        return null;
    }





}


